/**
 * 消息总线-渠道管理-渠道管理/渠道注册
 * 2019-06-12
 * @author: wdm
 */
import React, { Component } from "react";
import { Button, Form, message } from "antd";
import { connect } from "dva";
// import styles from "./index.less";
import RegisterBasic from "./components/RegisterBasic";
import WeChat from "./components/WeChat";
// import AppConfig from "./components/AppConfig";
// import BackstateConfig from './components/BackstateConfig';
import { CHANNEL_VALUE, getChannalPlaceholder } from "../../channelType";
import FixedBottomWrapper from "../../../components/FixedBottomWrapper";
import ImConfig from "./components/imConfig";
import LanXinPage from "./components/lan-xin";
import MailConfig from "./components/MailConfig/index";
import MessageConfig from "./components/MessageConfig";

@connect(stores => ({
  coldata: stores.user,
  channelDictionaryModel: stores.channelDictionaryModel,
  channelData: stores.channelModel
}))
@Form.create()
class channelRegister extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chanleType: "",
      pushChannelId: "",
      icon: "",
      ownerDeptName: "",
      detail: null
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {}
    });

    const { search } = location;
    // let pushChannelId = "";
    if (search) {
      const [, pushChannelId] = search.split("=");
      this.setState(
        {
          pushChannelId
        },
        () => {
          dispatch({
            type: "channelModel/channelDetail",
            payload: { pushChannelId }
          }).then(
            ({
              datas: {
                apiName,
                apiUrl,
                apiHost,
                agentId,
                apiAppKey,
                apiAppSecret,
                appKey,
                appPackageName,
                appSecret,
                channelType,
                channeluuid,
                channelCode,
                channelSysType,
                corpId,
                chatId,
                corpSecret,
                dataPrivilege,
                defaultStatus,
                description,
                gcmFcmSecret,
                huaweiAppId,
                huaweiAppSecret,
                icon,
                owners,
                ownerDept,
                ownerDeptName,
                pushChannelDescription,
                webPackageName,
                xiaomiAppSecret,
                gongZhongNoName,
                method,
                mqAddress,
                groupId,
                topic,
                tag,
                accessKey,
                secretKey,
                useStatus,
                // 邮件扩展参数部分
                sendName,
                passWord,
                mailHost,
                mailPort,
                mailAgreement,
                params,
                // 短信扩展字段
                smsTemplateCode,
                endpoint
              }
            }) => {
              this.setState({
                personId: owners && owners[0] && owners[0].key,
                icon,
                detail: {
                  apiName,
                  apiUrl,
                  apiHost,
                  apiAppKey,
                  apiAppSecret,
                  method,
                  mqAddress,
                  groupId,
                  topic,
                  tag,
                  accessKey,
                  secretKey,
                  useStatus,
                  // 邮件扩展字段
                  sendName,
                  passWord,
                  mailHost,
                  mailPort,
                  mailAgreement: String(mailAgreement),
                  emailParams: (params && params.length) || [],
                  // 短信扩展字段
                  smsTemplateCode,
                  endpoint
                }
              });
              setTimeout(() => {
                this.props.form.setFieldsValue({
                  // apiName,
                  // apiUrl,
                  // apiHost,
                  agentId: `${agentId}`,
                  // apiAppKey,
                  // apiAppSecret,
                  appKey,
                  appPackageName,
                  appSecret,
                  channelType: `${channelType}`,
                  channeluuid,
                  channelCode,
                  channelSysType,
                  corpId,
                  chatId,
                  corpSecret,
                  dataPrivilege,
                  defaultStatus,
                  description,
                  gcmFcmSecret,
                  huaweiAppId,
                  huaweiAppSecret,
                  owners: owners && owners[0] && owners[0].name,
                  ownerDept,
                  pushChannelDescription,
                  webPackageName,
                  xiaomiAppSecret,
                  gongZhongNoName,
                  useStatus: useStatus === 1,
                  // method,
                  // mqAddress,
                  // groupId,
                  // topic,
                  // tag,
                  // accessKey,
                  // secretKey,
                  // email 字段默认值
                  sendName,
                  passWord,
                  mailHost,
                  mailPort,
                  mailAgreement: String(mailAgreement),
                  emailParams:
                    params && params.length
                      ? params.map(item => ({
                          id: item.id,
                          attributeCode: item.attributeCode,
                          attributeValue: item.attributeValue,
                          isDeleted: item.isDeleted
                        }))
                      : [],
                  // 短信扩展字段
                  smsTemplateCode,
                  endpoint
                });
                this.setState({
                  ownerDeptName
                });
              }, 0);
              if (channelSysType) {
                this.onSysTypeChange();
              }
              this.handleType(`${channelType}`);
            }
          );
        }
      );
    }
    // 新增时 默认渠道类型为“政务微信”，管理员为当前用户，归属部门为当前用户部门
    else {
      const initChannelType = CHANNEL_VALUE.MESSAGE;
      const { coldata = {} } = this.props;
      const { userInfo = {} } = coldata;
      this.setState({
        personId: userInfo.userId,
        ownerDeptName: userInfo.departmentName
      });
      this.props.form.setFieldsValue({
        channelType: initChannelType,
        owners: userInfo.userName,
        ownerDept: userInfo.department,
        useStatus: true
      });
      this.handleType(initChannelType);
    }
  }

  handleType = value => {
    this.setState({
      chanleType: value
    });
  };

  onBack = () => {
    const { history } = this.props;
    history.goBack(-1);
    /*
    Modal.confirm({
      title: "是否直接关闭该渠道注册？",
      onOk: () => {
        history.push("/messageCenter/channelManager/channelList");
      },
      onCancel: () => { }
    });
    */
  };

  omit = (obj = {}, keys = []) => {
    const newObj = {};
    Object.keys(obj).forEach(key => {
      if (keys.indexOf(key) === -1) {
        newObj[key] = obj[key];
      }
    });
    return newObj;
  };

  // 保存/提交
  handleSubmit = (e, type) => {
    const {
      commitVlaue = false,
      chanleType,
      pushChannelId,
      ownerDeptName
    } = this.state;
    if (chanleType === CHANNEL_VALUE.SYSTEM && !commitVlaue) {
      message.info("请先进行联通性测试");
    } else {
      const { history } = this.props;
      const { personId, icon: stateicon } = this.state;
      e.preventDefault();
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const temp = values.owners;
          const emailParams = values.emailParams || [];
          const icon =
            values.icon &&
            values.icon[0] &&
            values.icon[0].response &&
            values.icon[0].response.datas
              ? values.icon[0].response.datas
              : stateicon;
          const t = {
            owners: [{ key: personId, name: temp }]
          };
          const { dispatch } = this.props;

          dispatch({
            type:
              type === "save"
                ? "channelRegisterModel/save"
                : "channelRegisterModel/commit",
            payload: {
              ...values,
              ...t,
              useStatus: values.useStatus ? 1 : 0,
              emailParams: emailParams.map(param => {
                // 服务端返回的 id 是数值型
                // 需要对前端增加 id 的记录提交前去除 id
                if (typeof param.id !== "number") {
                  return this.omit(param, ["id"]);
                }
                return param;
              }),
              icon,
              pushChannelId,
              ownerDeptName
            }
          }).then(res => {
            if (res.success) {
              message.success("操作成功");
              history.push("/messageCenter/channelManager/channelList");
            } else {
              message.error(res.errMsg ? res.errMsg : "操作失败");
            }
          });
        }
      });
    }
  };

  getPass = e => {
    this.setState({
      personId: e[0]
    });
  };

  commitEnable = e => {
    this.setState({
      commitVlaue: e
    });
  };

  changeOwnerDepatName = value => {
    this.setState({
      ownerDeptName: value
    });
  };

  onSysTypeChange() {
    setTimeout(() => {
      this.props.form.setFieldsValue(this.state.detail);
    }, 200);
  }

  render() {
    const { chanleType, icon, pushChannelId } = this.state;
    const { form, channelDictionaryModel = {}, history } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    const { personId } = this.state;
    return (
      <FixedBottomWrapper
        footer={
          <React.Fragment>
            <Button onClick={this.onBack} style={{ marginLeft: "20px" }}>
              取消
            </Button>
            {/* <Button
              style={{ marginLeft: 8, marginRight: 16 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e, 'save')}>
              保存
            </Button> */}
            <Button
              type="primary"
              style={{ marginLeft: 8, marginRight: 16 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e, "submit")}
            >
              保存
            </Button>
          </React.Fragment>
        }
      >
        <RegisterBasic
          form={form}
          handleType={this.handleType}
          chanleType={chanleType}
          channelsTypesData={channelsTypesData}
          getPass={this.getPass}
          changeOwnerDepatName={this.changeOwnerDepatName}
        />
        {/* {chanleType === CHANNEL_VALUE.SYSTEM && (
          <BackstateConfig
            form={form}
            personId={personId}
            history={history}
            commitEnable={this.commitEnable}
          />
        )} */}
        {chanleType === CHANNEL_VALUE.SYSTEM && (
          <ImConfig
            form={form}
            personId={personId}
            pushChannelId={pushChannelId}
            history={history}
            commitEnable={this.commitEnable}
            onTypeChange={() => this.onSysTypeChange()}
          />
        )}
        {(chanleType === CHANNEL_VALUE.DING_TALK ||
          chanleType === CHANNEL_VALUE.DING_ROBOT_TALK ||
          chanleType === CHANNEL_VALUE.DING_QUN_TALK) && (
          <WeChat
            imageUrl={icon}
            form={form}
            chanleType={chanleType}
            handleSubmit={this.handleSubmit}
            getChannelPlaceholder={getChannalPlaceholder}
          />
        )}
        {chanleType === CHANNEL_VALUE.MAIL && (
          <MailConfig
            form={form}
            chanleType={chanleType}
            handleSubmit={this.handleSubmit}
          />
        )}
        {chanleType === CHANNEL_VALUE.MESSAGE && (
          <MessageConfig
            form={form}
            chanleType={chanleType}
            handleSubmit={this.handleSubmit}
          />
        )}
        {(chanleType === CHANNEL_VALUE.LAN_XIN || chanleType === CHANNEL_VALUE.LAN_XIN_PLUS) && (
          <LanXinPage
            form={form}
            chanleType={chanleType}
            handleSubmit={this.handleSubmit}
          />
        )}
      </FixedBottomWrapper>
    );
  }
}

export default channelRegister;
